<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>数据库中间件shardingsphere-proxy |  麦田麦穗</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    </head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-数据库中间件shardingsphere"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  数据库中间件shardingsphere-proxy
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/25/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%B8%AD%E9%97%B4%E4%BB%B6shardingsphere/" class="article-date">
  <time datetime="2022-02-25T09:04:26.000Z" itemprop="datePublished">2022-02-25</time>
</a>   
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">1.4k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">6 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>坦白说80%的程序员的80%工作都是在与数据库打交道，显然数据库工作无比的重要。当数据量不大的时候似乎一切都不是问题,一旦数据量变大，程序员的挑战就变得越来越大。</p>
<p>当单表数据超过8千万，普通的加索引可能效果已经不会太好了。这个时候通常的解决办法是分库分表，也就是老生常谈的<code>sharding</code>.</p>
<p>今天我们来看看<code>shardingsphere</code>的解决方案。</p>
<span id="more"></span>

<p>官方文档：<a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.0/en/overview/">https://shardingsphere.apache.org/document/5.1.0/en/overview/</a></p>
<p>当前<code>shardingsphere</code>有3个产品</p>
<ul>
<li>ShardingSphere-JDBC</li>
<li>ShardingSphere-Proxy</li>
<li>ShardingSphere-Sidecar(TODO)</li>
</ul>
<p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20220225175604.png" alt=""></p>
<p><code>ShardingSphere-Sidecar</code>还在todo，我们暂且不讨论。当前ShardingSphere在github有15k的star，可见应该还是广受大家认可的。</p>
<p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20220225175742.png" alt=""></p>
<p><code>ShardingSphere-JDBC</code>是java的类库与应用程序和语言绑定，<code>ShardingSphere-Proxy</code>是中间代理与语言无关。</p>
<p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20220225173123.png" alt=""></p>
<p>从官网的蓝图来看，这是一个较新的项目，同时开发团队有着长远的规划。</p>
<h2 id="产品架构"><a href="#产品架构" class="headerlink" title="产品架构"></a>产品架构</h2><p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20220225174114.png" alt=""></p>
<p>从这张产品架构图我们可以看到大致的一些产品功能：</p>
<ul>
<li>sql审计</li>
<li>sql防火墙</li>
<li>分片</li>
<li>读写分离</li>
<li>DB负载均衡</li>
<li>伸缩拓展</li>
<li>影子库</li>
</ul>
<h2 id="分片"><a href="#分片" class="headerlink" title="分片"></a>分片</h2><p>我们来体验下<code>ShardingSphere-Proxy</code>的sharding。</p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p>从官网的下载页面可以下到二进制的程序，如果你是使用mysql则还需要下载jdbc驱动，这些安装都很简单。</p>
<h3 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h3><p>主要工作是在配置上面。为了方便测试，我们假设的场景是只分表不分库。</p>
<p>我们将订单表t_order按user_id%2分2张表,t_order_0和t_order_1。</p>
<p>我们要对2个配置文件进行配置。</p>
<ol>
<li>server.yaml</li>
</ol>
<p><code>server.yaml</code>主要是对ShardingSphere-Proxy本身的服务配置。</p>
<pre class="language-yaml" data-language="yaml"><code class="language-yaml"><span class="token key atrule">rules</span><span class="token punctuation">:</span>
 <span class="token punctuation">-</span> <span class="token tag">!AUTHORITY</span>
   <span class="token key atrule">users</span><span class="token punctuation">:</span>
     <span class="token punctuation">-</span> root@%<span class="token punctuation">:</span><span class="token number">123456</span>
     <span class="token punctuation">-</span> sharding@<span class="token punctuation">:</span>sharding
   <span class="token key atrule">provider</span><span class="token punctuation">:</span>
     <span class="token key atrule">type</span><span class="token punctuation">:</span> ALL_PRIVILEGES_PERMITTED
 <span class="token punctuation">-</span> <span class="token tag">!TRANSACTION</span>
   <span class="token key atrule">defaultType</span><span class="token punctuation">:</span> XA
   <span class="token key atrule">providerType</span><span class="token punctuation">:</span> Atomikos
 <span class="token punctuation">-</span> <span class="token tag">!SQL_PARSER</span>
   <span class="token key atrule">sqlCommentParseEnabled</span><span class="token punctuation">:</span> <span class="token boolean important">true</span>
   <span class="token key atrule">sqlStatementCache</span><span class="token punctuation">:</span>
     <span class="token key atrule">initialCapacity</span><span class="token punctuation">:</span> <span class="token number">2000</span>
     <span class="token key atrule">maximumSize</span><span class="token punctuation">:</span> <span class="token number">65535</span>
     <span class="token key atrule">concurrencyLevel</span><span class="token punctuation">:</span> <span class="token number">4</span>
   <span class="token key atrule">parseTreeCache</span><span class="token punctuation">:</span>
     <span class="token key atrule">initialCapacity</span><span class="token punctuation">:</span> <span class="token number">128</span>
     <span class="token key atrule">maximumSize</span><span class="token punctuation">:</span> <span class="token number">1024</span>
     <span class="token key atrule">concurrencyLevel</span><span class="token punctuation">:</span> <span class="token number">4</span>

<span class="token key atrule">props</span><span class="token punctuation">:</span>
 <span class="token key atrule">max-connections-size-per-query</span><span class="token punctuation">:</span> <span class="token number">1</span>
 <span class="token key atrule">kernel-executor-size</span><span class="token punctuation">:</span> <span class="token number">16</span>  <span class="token comment"># Infinite by default.</span>
 <span class="token key atrule">proxy-frontend-flush-threshold</span><span class="token punctuation">:</span> <span class="token number">128</span>  <span class="token comment"># The default value is 128.</span>
 <span class="token key atrule">proxy-opentracing-enabled</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
 <span class="token key atrule">proxy-hint-enabled</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
 <span class="token key atrule">sql-show</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
 <span class="token key atrule">check-table-metadata-enabled</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
 <span class="token key atrule">show-process-list-enabled</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
   <span class="token comment"># Proxy backend query fetch size. A larger value may increase the memory usage of ShardingSphere Proxy.</span>
   <span class="token comment"># The default value is -1, which means set the minimum value for different JDBC drivers.</span>
 <span class="token key atrule">proxy-backend-query-fetch-size</span><span class="token punctuation">:</span> <span class="token number">-1</span>
 <span class="token key atrule">check-duplicate-table-enabled</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
 <span class="token key atrule">proxy-frontend-executor-size</span><span class="token punctuation">:</span> <span class="token number">0</span> <span class="token comment"># Proxy frontend executor size. The default value is 0, which means let Netty decide.</span>
   <span class="token comment"># Available options of proxy backend executor suitable: OLAP(default), OLTP. The OLTP option may reduce time cost of writing packets to client, but it may increase the latency of SQL execution</span>
   <span class="token comment"># and block other clients if client connections are more than `proxy-frontend-executor-size`, especially executing slow SQL.</span>
 <span class="token key atrule">proxy-backend-executor-suitable</span><span class="token punctuation">:</span> OLAP
 <span class="token key atrule">proxy-frontend-max-connections</span><span class="token punctuation">:</span> <span class="token number">0</span> <span class="token comment"># Less than or equal to 0 means no limitation.</span>
 <span class="token key atrule">sql-federation-enabled</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
   <span class="token comment"># Available proxy backend driver type: JDBC (default), ExperimentalVertx</span>
 <span class="token key atrule">proxy-backend-driver-type</span><span class="token punctuation">:</span> JDBC</code></pre>

<p><code>users:</code> 定义了代理的连接信息。<code>root@%:123456</code>代表用户名root密码123456和在0.0.0.0上监听。</p>
<ol start="2">
<li>config-sharding.yaml</li>
</ol>
<p><code>config-sharding.yaml</code>定义了分库分表的算法信息。</p>
<pre class="language-yaml" data-language="yaml"><code class="language-yaml"><span class="token key atrule">schemaName</span><span class="token punctuation">:</span> db_test

<span class="token key atrule">dataSources</span><span class="token punctuation">:</span>
 <span class="token key atrule">ds_0</span><span class="token punctuation">:</span>
   <span class="token key atrule">url</span><span class="token punctuation">:</span> jdbc<span class="token punctuation">:</span>mysql<span class="token punctuation">:</span>//127.0.0.1<span class="token punctuation">:</span>3306/db_test<span class="token punctuation">?</span>serverTimezone=UTC<span class="token important">&amp;useSSL=false</span>
   <span class="token key atrule">username</span><span class="token punctuation">:</span> test_rw
   <span class="token key atrule">password</span><span class="token punctuation">:</span> ko<span class="token important">*0^fwZtQ2nZv</span>
   <span class="token key atrule">connectionTimeoutMilliseconds</span><span class="token punctuation">:</span> <span class="token number">30000</span>
   <span class="token key atrule">idleTimeoutMilliseconds</span><span class="token punctuation">:</span> <span class="token number">60000</span>
   <span class="token key atrule">maxLifetimeMilliseconds</span><span class="token punctuation">:</span> <span class="token number">1800000</span>
   <span class="token key atrule">maxPoolSize</span><span class="token punctuation">:</span> <span class="token number">50</span>
   <span class="token key atrule">minPoolSize</span><span class="token punctuation">:</span> <span class="token number">1</span>

<span class="token key atrule">rules</span><span class="token punctuation">:</span>
<span class="token punctuation">-</span> <span class="token tag">!SHARDING</span>
 <span class="token key atrule">tables</span><span class="token punctuation">:</span>
   <span class="token key atrule">t_order</span><span class="token punctuation">:</span>
     <span class="token key atrule">actualDataNodes</span><span class="token punctuation">:</span> ds_0.t_order_$<span class="token punctuation">&#123;</span>0..1<span class="token punctuation">&#125;</span>
     <span class="token key atrule">tableStrategy</span><span class="token punctuation">:</span>
       <span class="token key atrule">standard</span><span class="token punctuation">:</span>
         <span class="token key atrule">shardingColumn</span><span class="token punctuation">:</span> user_id
         <span class="token key atrule">shardingAlgorithmName</span><span class="token punctuation">:</span> t_order_inline
 <span class="token key atrule">bindingTables</span><span class="token punctuation">:</span>
   <span class="token punctuation">-</span> t_order
 <span class="token key atrule">defaultDatabaseStrategy</span><span class="token punctuation">:</span>
   <span class="token key atrule">none</span><span class="token punctuation">:</span>
 <span class="token key atrule">defaultTableStrategy</span><span class="token punctuation">:</span>
   <span class="token key atrule">none</span><span class="token punctuation">:</span>
 
 <span class="token key atrule">shardingAlgorithms</span><span class="token punctuation">:</span>
   <span class="token key atrule">t_order_inline</span><span class="token punctuation">:</span>
     <span class="token key atrule">type</span><span class="token punctuation">:</span> INLINE
     <span class="token key atrule">props</span><span class="token punctuation">:</span>
       <span class="token key atrule">algorithm-expression</span><span class="token punctuation">:</span> t_order_$<span class="token punctuation">&#123;</span>user_id % 2<span class="token punctuation">&#125;</span>

 <span class="token key atrule">scalingName</span><span class="token punctuation">:</span> default_scaling
 <span class="token key atrule">scaling</span><span class="token punctuation">:</span>
   <span class="token key atrule">default_scaling</span><span class="token punctuation">:</span>
     <span class="token key atrule">input</span><span class="token punctuation">:</span>
       <span class="token key atrule">workerThread</span><span class="token punctuation">:</span> <span class="token number">40</span>
       <span class="token key atrule">batchSize</span><span class="token punctuation">:</span> <span class="token number">1000</span>
       <span class="token key atrule">rateLimiter</span><span class="token punctuation">:</span>
         <span class="token key atrule">type</span><span class="token punctuation">:</span> QPS
         <span class="token key atrule">props</span><span class="token punctuation">:</span>
           <span class="token key atrule">qps</span><span class="token punctuation">:</span> <span class="token number">50</span>
     <span class="token key atrule">output</span><span class="token punctuation">:</span>
       <span class="token key atrule">workerThread</span><span class="token punctuation">:</span> <span class="token number">40</span>
       <span class="token key atrule">batchSize</span><span class="token punctuation">:</span> <span class="token number">1000</span>
       <span class="token key atrule">rateLimiter</span><span class="token punctuation">:</span>
         <span class="token key atrule">type</span><span class="token punctuation">:</span> TPS
         <span class="token key atrule">props</span><span class="token punctuation">:</span>
           <span class="token key atrule">tps</span><span class="token punctuation">:</span> <span class="token number">2000</span>
     <span class="token key atrule">streamChannel</span><span class="token punctuation">:</span>
       <span class="token key atrule">type</span><span class="token punctuation">:</span> MEMORY
       <span class="token key atrule">props</span><span class="token punctuation">:</span>
         <span class="token key atrule">block-queue-size</span><span class="token punctuation">:</span> <span class="token number">10000</span>
     <span class="token key atrule">completionDetector</span><span class="token punctuation">:</span>
       <span class="token key atrule">type</span><span class="token punctuation">:</span> IDLE
       <span class="token key atrule">props</span><span class="token punctuation">:</span>
         <span class="token key atrule">incremental-task-idle-minute-threshold</span><span class="token punctuation">:</span> <span class="token number">30</span>
     <span class="token key atrule">dataConsistencyChecker</span><span class="token punctuation">:</span>
       <span class="token key atrule">type</span><span class="token punctuation">:</span> DATA_MATCH
       <span class="token key atrule">props</span><span class="token punctuation">:</span>
         <span class="token key atrule">chunk-size</span><span class="token punctuation">:</span> <span class="token number">1000</span></code></pre>

<p><code>schemaName</code>非常重要，代表逻辑库名。</p>
<p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20220225182212.png" alt=""></p>
<p>我们通过mysql cli连接上去可以看到db名称即为<code>schemaName</code>定义的值。</p>
<p>我们定义了一个数据源ds_0映射到物理库db_test。</p>
<p><code>t_order</code>逻辑表映射到真实表t_order_0和t_order_1, <code>shardingColumn</code>为user_id,<code>shardingAlgorithmName</code>为t_order_inline</p>
<h3 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h3><p>接下来我们来写一段脚本测试下，主要测试2个场景。</p>
<ul>
<li>跨表查询数据聚合</li>
<li>带分片字段的分片查询</li>
</ul>
<p>对应的sql分别是</p>
<pre class="language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token keyword">from</span> t_order<span class="token punctuation">;</span>
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> t_order <span class="token keyword">where</span> user_id <span class="token operator">=</span> <span class="token number">12</span><span class="token punctuation">;</span></code></pre>

<p>对应的java代码是</p>
<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>vison<span class="token punctuation">.</span>jpal<span class="token punctuation">.</span>queryprocess</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span><span class="token class-name">Connection</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span><span class="token class-name">DriverManager</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span><span class="token class-name">ResultSet</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span><span class="token class-name">Statement</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">ArrayList</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">HashMap</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">List</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">Map</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>logging<span class="token punctuation">.</span>log4j<span class="token punctuation">.</span></span><span class="token class-name">LogManager</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>logging<span class="token punctuation">.</span>log4j<span class="token punctuation">.</span></span><span class="token class-name">Logger</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">Properties</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestSharding</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">Logger</span> logger <span class="token operator">=</span> <span class="token class-name">LogManager</span><span class="token punctuation">.</span><span class="token function">getLogger</span><span class="token punctuation">(</span><span class="token class-name">ThreadQuery</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">//2. 获得数据库连接</span>
        logger<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"开始...."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token string">"jdbc:mysql://www-dev.h66.cn:3307/db_test"</span><span class="token punctuation">,</span> <span class="token string">"root"</span><span class="token punctuation">,</span> <span class="token string">"123456"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//3.操作数据库，实现增删改查</span>
        <span class="token class-name">Statement</span> stmt <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//count</span>
        <span class="token class-name">Integer</span> user_id <span class="token operator">=</span> <span class="token number">12</span><span class="token punctuation">;</span>
        <span class="token class-name">ResultSet</span> countQuery <span class="token operator">=</span> stmt<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token string">"SELECT count(*) FROM t_order"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//        System.out.print(rs.getC);</span>
        <span class="token comment">//如果有数据，rs.next()返回true</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>countQuery<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"数据总数: %d%n"</span><span class="token punctuation">,</span>countQuery<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Map</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span><span class="token punctuation">></span></span> listUser <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">ResultSet</span> shardingQuery <span class="token operator">=</span> stmt<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token string">"SELECT * FROM t_order where user_id = %s"</span><span class="token punctuation">,</span> user_id<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>shardingQuery<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> user <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            user<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"order_no"</span><span class="token punctuation">,</span> shardingQuery<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"order_no"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            user<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"user_id"</span><span class="token punctuation">,</span> shardingQuery<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"user_id"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            listUser<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span>listUser<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
</code></pre>

<p>得出结果</p>
<p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20220225183624.png" alt=""></p>
<h2 id="收益"><a href="#收益" class="headerlink" title="收益"></a>收益</h2><p>总结下我们使用<code>ShardingSphere-Proxy</code>能给我们带来哪些好处</p>
<ul>
<li>使用代理的方式，对项目代码无入侵，与语言无关。任何编程语言都能接入。</li>
<li>中间件代理帮忙处理了分库分表查询的问题并且能保障性能,这无疑解放了程序员对分库分表需求的担忧。当有分库分表的需求时，几乎还可以像操作单表那样操作。</li>
<li>负载均衡、读写分离、影子库表功能让程序性能、可靠性大大提升</li>
</ul>
<h2 id="风险"><a href="#风险" class="headerlink" title="风险"></a>风险</h2><ul>
<li>跨表查询数据聚合到底性能如何，最佳能支持多少表多少数据量的跨表查询，如何达到最佳性能这些问题都需要考虑</li>
</ul>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          Donate
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://visonforcoding.xyz/2022/02/25/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%B8%AD%E9%97%B4%E4%BB%B6shardingsphere/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mysql/" rel="tag">mysql</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/03/27/%E5%8F%8D%E5%AF%B9%E4%B8%AD%E5%8F%B0/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            架构|反对中台
          
        </div>
      </a>
    
    
      <a href="/2022/02/23/%E9%98%BF%E9%87%8Cmysql%E4%B8%AD%E9%97%B4%E4%BB%B6%E5%A4%9A%E8%A1%A8%E6%9F%A5%E8%AF%A2%E6%A8%A1%E5%9E%8B/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">数据|阿里mysql中间件多表查询模型</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> vison
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="麦田麦穗"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%97%85%E8%A1%8C/">旅行</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://shenyu-vip.lofter.com">摄影</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/null">Gallery</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>Buy me a cup of coffee~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpeg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wallet.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>